package com.betty.cscams.service.impl;

import com.betty.cscams.constant.SysConstants;
import com.betty.cscams.dao.SysCaptchaMapper;
import com.betty.cscams.entity.SysCaptcha;
import com.betty.cscams.service.SysCaptchaService;
import com.google.code.kaptcha.Producer;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.beans.Transient;

@Service
public class SysCaptchaServiceImp implements SysCaptchaService {

    @Autowired
    private SysCaptchaMapper sysCaptchaMapper;
    @Autowired
    private Producer producer;
    @Autowired
    private SysMailServiceImpl sysMailService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void  sendMail(String username,String mail) throws Exception {
        SysCaptcha sysCaptcha = new SysCaptcha();
        // 生成文字验证码
        String text = producer.createText();
        //获取当前时间时间戳
        Long failureTime = System.currentTimeMillis() + SysConstants.VALID_TIME;
        sysCaptcha.setName(username);
        sysCaptcha.setCaptcha(text);
        sysCaptcha.setFailureTime(failureTime);
        sysCaptcha.setMail(mail);
        if(ObjectUtils.isEmpty(sysCaptchaMapper.selectByPrimaryKey(username))){
            sysCaptchaMapper.insert(sysCaptcha);
        }else{
            sysCaptchaMapper.updateByPrimaryKey(sysCaptcha);
        }
        String subject = "大学生综合测评系统验证码";
        String content = "Hey "+username+"!\n" +
                "\n" +
                "由于我们无法识别您的设备,因此需要进一步验证。要完成登录,请在无法识别的设备上输入验证码。\n" +
                "\n" +
                "验证码: "+text+"\n" +
                "\n" +
                "如果您未尝试登录您的账户,您的密码可能会被泄露。请立即修改一个轻度较高的密码。\n" +
                "\n" +
                "谢谢\n" +
                "大学生综合测评系统 团队";
        sysMailService.sendSimpleMail(mail,subject,content);
    }

    @Override
    public boolean vaildCaptcha(String username, String email, String captcha) {
        boolean flag = false;
        SysCaptcha sysCaptcha = sysCaptchaMapper.selectByPrimaryKey(username);
        if(ObjectUtils.isNotEmpty(sysCaptcha) && ObjectUtils.isNotEmpty(sysCaptcha.getFailureTime())){
            if(System.currentTimeMillis() < sysCaptcha.getFailureTime()){
                flag = true;
            }
        }
        return flag;
    }

    @Override
    public void sendResetPwdMail(String username, String email, String password) throws Exception {
        String subject = "大学生综合测评系统重置密码";
        String content = "Hey "+username+"!\n" +
                "\n" +
                "您在大学生综合测评系统的子账户密码已重置，\n" +
                "\n" +
                "密码: "+password+"\n" +
                "\n" +
                "请登录系统后进行修改\n" +
                "\n" +
                "谢谢\n" +
                "大学生综合测评系统 团队";
        sysMailService.sendSimpleMail(email,subject,content);
    }


}
